//--------------------------------------------------------------
//
// Qizhi Zhang 
// ezhung@gmail.com
// http://www.moorwind.com
//
//--------------------------------------------------------------
package reader.controller
{
	import com.moorwind.gFeed.GFeedLoader;
	import com.moorwind.gFeed.event.GFeedLoaderEvent;
	
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;
	
	import reader.ApplicationFacade;

	public class SearchFeedCommand extends SimpleCommand implements ICommand
	{
		
		//////////////////////////////////////////////////////////////////////////////
		//methods
		
		override public function execute(notification:INotification):void
		{
			var keyword:String = notification.getBody().toString();
			var gFeed:GFeedLoader = new GFeedLoader();
			gFeed.addEventListener(GFeedLoaderEvent.GFEED_FIND_COMPLETE, onGetFind_handler);
			gFeed.addEventListener(GFeedLoaderEvent.GFEED_ERROR, onGetFindError_handler);
			gFeed.findFeed(keyword);
		}
		
		//////////////////////////////////////////////////////////////////////////////
		//events
		
		private function onGetFind_handler(e:GFeedLoaderEvent):void
		{
			var gFeed:GFeedLoader = e.target as GFeedLoader; 
			gFeed.removeEventListener(GFeedLoaderEvent.GFEED_FIND_COMPLETE, onGetFind_handler);
			gFeed.removeEventListener(GFeedLoaderEvent.GFEED_ERROR, onGetFindError_handler);
			
			sendNotification(ApplicationFacade.FEEDS_SEARCHED, e.gFindResponse);
		}
		
		private function onGetFindError_handler(e:GFeedLoaderEvent):void
		{
			var gFeed:GFeedLoader = e.target as GFeedLoader; 
			gFeed.removeEventListener(GFeedLoaderEvent.GFEED_FIND_COMPLETE, onGetFind_handler);
			gFeed.removeEventListener(GFeedLoaderEvent.GFEED_ERROR, onGetFindError_handler);
			
			sendNotification(ApplicationFacade.FEEDS_SEARCHED, null);
		}
	}
}